package cn.sinokj.party.chineseFourParty.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import cn.sinokj.party.chineseFourParty.R;
import cn.sinokj.party.chineseFourParty.activity.IndexImageWebActivity;
import cn.sinokj.party.chineseFourParty.adapter.XListAdapter;
import cn.sinokj.party.chineseFourParty.app.App;
import cn.sinokj.party.chineseFourParty.bean.IndexImage;
import cn.sinokj.party.chineseFourParty.fragment.base.BaseFragment;
import cn.sinokj.party.chineseFourParty.service.HttpConstants;
import cn.sinokj.party.chineseFourParty.service.HttpDataService;
import cn.sinokj.party.chineseFourParty.view.dialog.DialogShow;
import cn.sinokj.party.chineseFourParty.view.xlist.XListView;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Created by Administrator on 2018/4/26.
 */

public class NewsFragment extends BaseFragment {
    public static final int TO_CHANGE_READ_STATUS = 3;
    private static final int REFRESH = 0;
    private static final int INIT_DATA = 1;
    private static final int LOAD_MORE = 2;
    private static final int QUERY_SIZE = 10;
    @BindView(R.id.xlist_listview)
    XListView dataListView;
    Unbinder unbinder;
    private int nId;
    private int nPage = 1;
    private String functionType;
    private IndexImage indexImage;
    private XListAdapter xListAdapter;
    private List<IndexImage> dataList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_news, container, false);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this, view);
        dataListView.setXListViewListener(ixListViewListener);
        dataListView.setOnItemClickListener(onItemClickListener);
        new Thread(new LoadDataThread(INIT_DATA)).start();
        return view;
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // XListView 默认position为1
            indexImage = dataList.get(position - 1);
            Intent intent = new Intent(getActivity(), IndexImageWebActivity.class);
            intent.putExtra("url", indexImage.url);
            intent.putExtra("icon", indexImage.vcPath);
            intent.putExtra("newsTitle", indexImage.vcTitle);
            intent.putExtra("topTitle", functionType);
            intent.putExtra("nShared", indexImage.nShared);
            intent.putExtra("describe", indexImage.vcDescribe);
            intent.putExtra("isRush", true);
            startActivity(intent);
        }
    };

    private XListView.IXListViewListener ixListViewListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
            nPage = 1;
            DialogShow.showRoundProcessDialog(getActivity());
            new Thread(new LoadDataThread(REFRESH)).start();
        }

        @Override
        public void onLoadMore() {
            nPage += 1;
            new Thread(new LoadDataThread(LOAD_MORE)).start();
        }
    };

    @Override
    protected Map<String, JSONObject> getDataFunction(int what, int arg1, int arg2, Object obj) {
        if (getUserVisibleHint()) {
            if (what == TO_CHANGE_READ_STATUS) {
                if (indexImage != null) {
                    Log.e("indexImage.nId", "indexImage.nId" + indexImage.nId);
                    return HttpDataService.getSingleReadStatus(String.valueOf(indexImage.nId));//以前是indexImage.vcType
                } else {
                    return null;
                }
            }
        }
        return HttpDataService.getNews(functionType, String.valueOf(nPage), String.valueOf(QUERY_SIZE),
                App.nCommitteeId, nId + "");
    }

    @Override
    protected void httpHandlerResultData(Message msg, JSONObject jsonObject) {
        if (msg.what == TO_CHANGE_READ_STATUS) {
            indexImage.nStatus = (jsonObject.optInt(HttpConstants.RESULT));
            indexImage.nclick = Integer.valueOf(jsonObject.optString("nClick"));
            xListAdapter.notifyDataSetChanged();
            return;
        }
        JSONArray jsonArray = jsonObject.optJSONArray(HttpConstants.OBJECTS);
        List<IndexImage> list = new Gson().fromJson(jsonArray.toString(), new TypeToken<List<IndexImage>>() {
        }.getType());
        switch (msg.what) {
            case REFRESH:
                dataListView.stopRefresh();
            case INIT_DATA:
                if (list.size() == 0 && getUserVisibleHint()) {
                    Toast.makeText(getActivity(), "没有查到相关信息", Toast.LENGTH_SHORT).show();
                    return;
                }
                dataList = new ArrayList<IndexImage>();
                dataList.addAll(list);
                xListAdapter = new XListAdapter(getActivity(), dataList);
                dataListView.setAdapter(xListAdapter);
                break;
            case LOAD_MORE:
                dataList.addAll(list);
                xListAdapter.notifyDataSetChanged();
                break;
        }
        dataListView.setPullLoadEnable(list.size() == QUERY_SIZE);
        DialogShow.closeDialog();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onEvent(Message msg) {
        switch (msg.what) {
            case 001:
                new Thread(new LoadDataThread(TO_CHANGE_READ_STATUS)).start();
                break;
        }
    }

    public void setNclass(int nId, String functionType) {
        this.nId = nId;
        this.functionType = functionType;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
